package model.environment;

import java.util.Date;
import java.util.List;

import model.Customer;
import model.XML;

public class Customers {
	private static List<Customer> customers = null;
	private static long lastUpdate = new Date().getTime();
	
	/**
	 * Gets all customers in the shopping network.
	 * @return A list of customers.
	 */
	public static List<Customer> getCustomers()
	{
		long timeSinceLastUpdate = new Date().getTime() - lastUpdate;
			
		if (customers == null || timeSinceLastUpdate > StaticInfo.UPDATE_TIMEOUT)
		{
			try {
				customers = XML.getCustomers();
				lastUpdate = new Date().getTime();
			}
			catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return customers;
	}
	
	/**
	 * Gets a customer from the cloud based on the customer's id.
	 * @param id The customer's id.
	 * @return The customer with the specified id.
	 */
	public static Customer getCustomer(int id) {
		Customer result = null;
		
		List<Customer> customers = getCustomers();
		
		for (Customer c : customers) {
			if (c.getCustomerID() == id) {
				result = c;
				break;
			}
		}
		
		return result;
	}
	
	/**
	 * Forces the customers list to update the next time getCustomers() is called.
	 */
	public static void resetCustomersList() {
		customers = null;
	}
}
